// 生产订单(MO)服务
// 基于MO.py和生产订单列表查询.xml的API接口实现

const axios = require('axios');

class MOService {
  constructor() {
    // 生产订单系统API配置
    this.baseURL = process.env.MO_API_BASE_URL || 'http://localhost:8080/api/mo';
    this.apiKey = process.env.MO_API_KEY || '';
    this.timeout = 10000; // 10秒超时
    
    // 创建axios实例
    this.client = axios.create({
      baseURL: this.baseURL,
      timeout: this.timeout,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': this.apiKey ? `Bearer ${this.apiKey}` : ''
      }
    });
    
    // 请求拦截器
    this.client.interceptors.request.use(
      (config) => {
        console.log(`🔗 MO API请求: ${config.method?.toUpperCase()} ${config.url}`);
        return config;
      },
      (error) => {
        console.error('❌ MO API请求失败:', error);
        return Promise.reject(error);
      }
    );
    
    // 响应拦截器
    this.client.interceptors.response.use(
      (response) => {
        console.log(`✅ MO API响应: ${response.config.url} - ${response.status}`);
        return response;
      },
      (error) => {
        console.error('❌ MO API响应错误:', error.response?.status, error.message);
        return Promise.reject(error);
      }
    );
  }
  
  /**
   * 查询生产订单列表
   * @param {Object} params 查询参数
   * @param {string} params.orderNumber 订单号 (支持模糊查询)
   * @param {string} params.materialCode 物料编码
   * @param {string} params.startDate 开始日期
   * @param {string} params.endDate 结束日期
   * @param {string} params.status 订单状态
   * @param {number} params.page 页码
   * @param {number} params.pageSize 每页大小
   * @returns {Promise<Object>} 订单列表
   */
  async getOrderList(params = {}) {
    try {
      // 如果有订单号查询参数，先清洗
      if (params.orderNumber) {
        const originalOrderNumber = params.orderNumber;
        params.orderNumber = this.cleanOrderNumber(params.orderNumber);
        console.log(`搜索订单号清洗: ${originalOrderNumber} -> ${params.orderNumber}`);
      }

      const response = await this.client.get('/orders', { params });

      return {
        success: true,
        data: {
          orders: response.data.orders || [],
          total: response.data.total || 0,
          page: response.data.page || 1,
          pageSize: response.data.pageSize || 20
        }
      };
    } catch (error) {
      console.error('获取生产订单列表失败:', error);

      // 真实生产环境 - 返回错误而不是模拟数据
      return {
        success: false,
        message: '获取生产订单列表失败',
        error: error.message,
        data: {
          orders: [],
          total: 0,
          page: 1,
          pageSize: 20
        }
      };
    }
  }
  
  /**
   * 清洗订单号
   * @param {string} orderNumber 原始订单号
   * @returns {string} 清洗后的订单号
   */
  cleanOrderNumber(orderNumber) {
    if (!orderNumber) return '';

    // 1. 去除首尾空格
    let cleaned = orderNumber.trim();

    // 2. 去除中间的空格和特殊字符
    cleaned = cleaned.replace(/[\s\-_]/g, '');

    // 3. 转换为大写
    cleaned = cleaned.toUpperCase();

    // 4. 如果是纯数字，自动添加SCDD前缀
    if (/^\d+$/.test(cleaned)) {
      cleaned = `SCDD${cleaned}`;
    }

    // 5. 如果以SCDD开头但后面不是数字，尝试修复
    if (cleaned.startsWith('SCDD') && cleaned.length > 4) {
      const numberPart = cleaned.substring(4).replace(/\D/g, '');
      if (numberPart) {
        cleaned = `SCDD${numberPart}`;
      }
    }

    return cleaned;
  }

  /**
   * 根据订单号获取订单详情
   * @param {string} orderNumber 订单号
   * @returns {Promise<Object>} 订单详情
   */
  async getOrderDetail(orderNumber) {
    try {
      // 清洗订单号
      const cleanedOrderNumber = this.cleanOrderNumber(orderNumber);
      console.log(`订单号清洗: ${orderNumber} -> ${cleanedOrderNumber}`);

      // 首先尝试调用用友生产订单查询API
      const yonyouResult = await this.queryYonyouOrder(cleanedOrderNumber);
      if (yonyouResult.success) {
        return yonyouResult;
      }

      // 如果用友API失败，尝试本地API
      const response = await this.client.get(`/orders/${cleanedOrderNumber}`);

      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('获取订单详情失败:', error);

      // 真实生产环境 - 返回错误而不是模拟数据
      return {
        success: false,
        message: `订单号 ${orderNumber} 未找到`,
        error: error.message
      };
    }
  }

  /**
   * 调用用友生产订单查询API
   * @param {string} orderNumber 订单号
   * @returns {Promise<Object>} 订单详情
   */
  async queryYonyouOrder(orderNumber) {
    try {
      const yonyouApiUrl = 'https://c3.yonyoucloud.com/iuap-api-gateway/yonbip/mfg/productionorder/list';
      const accessToken = process.env.YONYOU_ACCESS_TOKEN || 'your_access_token_here';

      const requestBody = {
        pageIndex: 1,
        pageSize: 10,
        code: orderNumber,
        isShowMaterial: true,
        isShowProcess: 0
      };

      const response = await axios.post(`${yonyouApiUrl}?access_token=${accessToken}`, requestBody, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        timeout: 10000 // 10秒超时
      });

      if (response.data && response.data.success && response.data.data && response.data.data.length > 0) {
        const orderData = response.data.data[0];

        // 提取订单产品信息
        const orderProduct = orderData.orderProduct && orderData.orderProduct.length > 0
          ? orderData.orderProduct[0]
          : {};

        // 提取自定义字段信息
        const productDefineDts = orderData.productDefineDts || {};

        return {
          success: true,
          data: {
            order_number: orderData.code || orderNumber,
            // 使用正确的字段映射
            material_code: orderProduct.productCode || orderProduct.productId?.code || '',
            product_name: orderProduct.productName || orderProduct.productId?.name || '',
            demand_category: productDefineDts.XS11 || orderData.transType?.name || '标准需求',
            customer_number: productDefineDts.XS15 || orderData.customer?.code || '',
            order_quantity: orderProduct.quantity || orderProduct.qty || 0,
            status: this.mapOrderStatus(orderData.status),
            plan_start_date: orderProduct.startDate ? orderProduct.startDate.split(' ')[0] : '',
            plan_end_date: orderProduct.finishDate ? orderProduct.finishDate.split(' ')[0] : '',
            created_date: orderData.vouchdate ? orderData.vouchdate.split(' ')[0] : '',
            // 额外信息
            org_name: orderData.org?.name || '',
            department_name: orderData.productionDepartment?.name || '',
            unit_name: orderProduct.productId?.measureUnit?.name || ''
          }
        };
      } else {
        console.log('用友API未找到订单:', orderNumber);
        return { success: false, message: '未找到订单信息' };
      }
    } catch (error) {
      console.error('调用用友API失败:', error.message);
      return { success: false, message: '用友API调用失败' };
    }
  }

  /**
   * 映射订单状态
   * @param {string|number} status 原始状态
   * @returns {string} 映射后的状态
   */
  mapOrderStatus(status) {
    const statusMap = {
      '0': '开立',
      '1': '已审核',
      '2': '已关闭',
      '3': '审核中',
      '4': '已锁定',
      '5': '已开工'
    };
    return statusMap[String(status)] || '未知状态';
  }
  
  /**
   * 搜索订单 (支持模糊匹配)
   * @param {string} query 搜索关键词
   * @param {number} limit 返回数量限制
   * @returns {Promise<Object>} 搜索结果
   */
  async searchOrders(query, limit = 10) {
    try {
      const response = await this.client.get('/orders/search', {
        params: { q: query, limit }
      });
      
      return {
        success: true,
        data: response.data.orders || []
      };
    } catch (error) {
      console.error('搜索订单失败:', error);

      // 真实生产环境 - 返回错误而不是模拟数据
      return {
        success: false,
        message: '搜索订单失败',
        error: error.message,
        data: []
      };
    }
  }
  
  /**
   * 获取物料信息
   * @param {string} materialCode 物料编码
   * @returns {Promise<Object>} 物料信息
   */
  async getMaterialInfo(materialCode) {
    try {
      const response = await this.client.get(`/materials/${materialCode}`);
      
      return {
        success: true,
        data: response.data
      };
    } catch (error) {
      console.error('获取物料信息失败:', error);

      // 真实生产环境 - 返回错误而不是模拟数据
      return {
        success: false,
        message: `物料编码 ${materialCode} 未找到`,
        error: error.message
      };
    }
  }

  // ========== 真实生产环境 - 禁止模拟数据 ==========
  // 所有模拟数据已删除，只允许真实API调用
}

module.exports = MOService;
